<?php
/**
 * Created by PhpStorm.
 * User: 虚空之翼 <183700295@qq.com>
 * Date: 16/5/20
 * Time: 09:14
 */

namespace app\admin\controller;


use app\admin\model\AuthGroupAccess;
use app\admin\model\Member;
use app\admin\model\WechatDepartment;
use app\admin\model\WechatDepartmentUser;
use app\admin\model\WechatTag;
use app\admin\model\WechatUser;
use app\admin\model\WechatUserTag;
use app\user\model\UcenterMember;
use com\wechat\QYWechat;
use think\Config;
use think\Db;
use think\Input;
use think\Log;

class Wechat extends Admin
{
    public function index() {

    }


    public function user() {
        $name = input('name');
        $map = ['name' => ['like', "%$name%"]];
        $list = WechatUser::where($map)->order('permission')->paginate(15);
        $department = WechatDepartment::column('id, name');

        foreach ($list as $key=>$value) {
            $departmentId = $value['department'];
            if($departmentId){
                $name = $department[$departmentId];
                $list[$key]['department'] = $name;
            }else{
                $list[$key]['department'] = "暂无";
            }
        }
        // 状态转化
        wechat_status_to_string($list);
        $this->assign('list', $list);
        $this->assign('department', $department);

        return $this->fetch();
    }


    /**
     * 同步通讯录用户
     */
    public function synchronizeUser() {
        $Wechat = new QYWechat(Config::get('user'));
        if($Wechat->errCode != 40001) {
            return $this->error("同步出错");
        }

        /* 同步部门 */
        $list = $Wechat->getDepartment();
        $new_users = [];
        /* 同步最顶级部门下面的用户 */
        foreach ($list['department'] as $key=>$value) {
            $users = $Wechat->getUserListInfo($value['id']);
            if($users['userlist']) {
                foreach ($users['userlist'] as $user) {
                    $data = [
                        'userid' => $user['userid'],
                        'name' => $user['name'],
                        'email' => $user['email'],
                        'position' => $user['position'],
                        'mobile' => $user['mobile'],
                        'gender' => $user['gender'],
                        'avatar' => $user['avatar'],
                        'department' => $user['department'][0], //只选第一个所属部门
                        'status' => $user['status'],
                        'isleader' => $user['isleader'],
                        'order' => $user['order'][0],
                    ];
                    if($user['extattr']['attrs']) {
                        foreach ($user['extattr']['attrs'] as $value) {
                            switch ($value['name']){
                                case "权限":
                                    $data['permission'] = $value['value'] ? $value['value'] : 5;
                                    break;
                                default:
                                    break;
                            }
                        }
                        $data['extattr'] = json_encode($user['extattr']);
                    }else {
                        $data['extattr'] = json_encode($user['extattr']);
                    }
                    $new_users[] = $data;
                    //存在则更新用户，不存在则新增用户
                    if(WechatUser::get(['userid'=>$user['userid']])) {
                        WechatUser::where(['userid'=>$user['userid']])->update($data);
                        $this->createAdminUser($data);
                    } else {
                        WechatUser::create($data);
                        $this->createAdminUser($data);
                    }
                }
                $sum[] = count($users['userlist']);
            }else {
                $sum[] = 0;
            }
        }
        $this->deleteDifferentUser($new_users); //删除老用户
        $number = array_sum($sum);
        return $number;
    }

    /**
     * 删除通讯录不存在用户
     * @param $new_users
     * @throws \think\Exception
     * @throws \think\Exception\DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\PDOException
     */
    private function deleteDifferentUser($new_users)
    {
        //新用户组
        $new = [];
        foreach ($new_users as $value) {
            $new[] = $value['userid'];
        }
        //老用户组
        $old = [];
        $old_users = WechatUser::all();
        foreach ($old_users as $key => $value) {
            $old[] = $value['userid'];
        }
        $diff = array_diff($old,$new); //获取不存在通讯录用户并删除
        if($diff) {
            foreach ($diff as $value) {
                $ucenteruser = UcenterMember::where('username', $value)->find();
                AuthGroupAccess::where('uid', $ucenteruser['id'])->delete(); //删除后台权限
                UcenterMember::where('username', $value)->delete(); //删除后台用户
                WechatUser::where('userid', $value)->delete(); //删除更新用户
            }
            Log::write("code:6,删除用户成功，共删除".count($diff));
        }else {
            Log::write("code:7,无不同用户，无需执行删除");
        }

    }

    /**
     * 同步部门
     */
    public function synchronizeDp(){
        $Wechat = new QYWechat(Config::get('user'));
        if($Wechat->errCode != 40001) {
            return $this->error("同步出错");
        }

        /* 同步部门 */
        $list = $Wechat->getDepartment();
        WechatDepartment::where('1=1')->delete();
        foreach ($list['department'] as $key=>$value) {
            WechatDepartment::create($value);
        }

        /* 同步部门-用户关系表 */
        WechatDepartmentUser::where('1=1')->delete();
        foreach ($list['department'] as $key=>$value) {
            $users = $Wechat->getUserListInfo($value['id']);
            foreach ($users['userlist'] as $user) {
                $data = ['departmentid'=>$value['id'], 'userid' => $user['userid']];    //微信通讯录同步取不到已分部门用户数据
                if(empty(WechatDepartmentUser::where($data)->find())){
                    WechatDepartmentUser::create($data);
                }
            }
        }

        $number = count($list['department']);

        return $number;
    }

    /**
     * 同步标签
     */
    public function synchronizeTag(){
        $Wechat = new QYWechat(Config::get('user'));
        if($Wechat->errCode != 40001) {
            return $this->error("同步出错");
        }

        /* 同步标签 */
        WechatTag::where('1=1')->delete();
        $tags = $Wechat->getTagList();
        foreach ($tags['taglist'] as $tag) {
            if(WechatTag::get(['tagid'=>$tag['tagid']])) {
                WechatTag::where(['tagid'=>$tag['tagid']])->update($tag);
            } else {
                WechatTag::create($tag);
            }
        }

        /* 同步标签-用户关系表 */
        WechatUserTag::where('1=1')->delete();
        foreach ($tags['taglist'] as $value) {
            $users = $Wechat->getTag($value['tagid']);
            if(empty($users['userlist'])){
                foreach ($users['partylist'] as $user){
                    $info = $Wechat->getUserListInfo($user);
                    foreach ($info['userlist'] as $val){
                        $data = ['tagid' => $value['tagid'],'userid' => $val['userid']];
                        if(empty(WechatUserTag::where($data)->find())){
                            WechatUserTag::create($data);
                        }
                    }
                };
            }else{
                foreach ($users['userlist'] as $user) {
                    $data = ['tagid'=>$value['tagid'], 'userid'=>$user['userid']];
                    if(empty(WechatUserTag::where($data)->find())){
                        WechatUserTag::create($data);
                    }
                }
            }
        }

        $number = count($tags['taglist']);

        return $number;
    }
    
    public function department(){
        $list = WechatDepartment::paginate(10);
        $this->assign('list', $list);

        return $this->fetch();
    }

    public function tag(){
        $list = WechatTag::paginate(10);
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     * 更新通讯录同时更新后台用户
     */
    protected function createAdminUser($data = '') {
//        $data = [
//            'userid' => 18768112486,
//            'mobile' => 18768112486,
//            'name' => '林二',
//            'email' => '123@qq.com',
//            'department' => [26],
//            'avatar' => 'http://p.qlogo.cn/bizmail/NPIX7ZJbTLcdVibeNO8EXgzbtjBdYqMb7eOZKqGyMdicibRHcydglhy0A/0',
//        ];
        if($data) {
            $UcenterMemberModel = new UcenterMember();
            $AuthGroupAccessModel = new AuthGroupAccess();
            $Member = new Member();
            $departmentModel = new WechatDepartment();
            $exist = UcenterMember::where('username',$data['userid'])->find();
            if($exist && $data) {
                $data_user = [
                    'username' => $exist['username'],
                    'password' => $exist['password'],
                    'email' => $data['email'] ? $data['email'] : $exist['email'],
                    'mobile' => $data['mobile'],
                ];
                $UcenterMemberModel->where(['id' => $exist['id']])->update($data_user);
                $res = $UcenterMemberModel->where(['id' => $exist['id']])->find();
            }else {
                $data_user = [
                    'username' => $data['userid'],
                    'password' => 123456,
                    'email' => $data['email'] ? $data['email'] : $data['userid'].'@sysw.com',
                    'mobile' => $data['mobile'],
                    'nickname' => $data['name'],
                ];
                $res = $UcenterMemberModel->create($data_user);
            }
            if($res) {
                //更新member 数据 新增头像
                if($data['avatar']) {
                    $Member->save(['header' => $data['avatar']],['id' => $res['id']]);
                }
                //新增用户权限
                if($data['department']) {
                    $data_auth = [
                        'uid' => $res['id'],
                    ];
                    $dp = $departmentModel->where(['id' => $data['department']])->find();
                    if($dp['id'] == 10) {
                        $data_auth['group_id'] = 1; //领导
                    }else if ($dp['id'] == 14) {
                        $data_auth['group_id'] = 2; //文印
                    }else if ($dp['id'] == 5 ) {
                        $data_auth['group_id'] = 3; //办公室
                    }else {
                        $data_auth['group_id'] = 4; //资源管理
                    }
                    $info = $AuthGroupAccessModel->where($data_auth)->find();
                    if($info) {
                        $AuthGroupAccessModel->update($data_auth,['id' => $info['id']]);
                        Log::write("code:1,同步插入后台，用户".$data['userid']."更新权限成功");
                    }else {
                        $AuthGroupAccessModel->create($data_auth);
                        Log::write("code:2,同步插入后台，用户".$data['userid']."新增权限成功");
                    }
                }else {
                    Log::write("code:3,同步插入后台用户失败，用户".$data['userid']."不存在部门");
                }
            }else {
                Log::write("code:4,同步插入后台用户失败，用户".$data['userid']."创建失败");
            }
        }else {
            Log::write("code:5,同步插入后台用户失败，未传递相关用户值");
        }
    }

    /**
     * 一键同步及分步同步
     * type：1用户 2部门 3标签 0 一键同步
     */
    public function oneclicksync() {
        $type = input('type');
        switch ($type) {
            case 1:
                $number = $this->synchronizeUser();
                $msg = "同步用户数:".$number."!";
                break;
            case 2:
                $number = $this->synchronizeDp();
                $msg = "同步部门数:".$number."!";
                break;
            case 3:
                $number = $this->synchronizeTag();
                $msg = "同步标签数:".$number."!";
                break;
            default:
                $number1 = $this->synchronizeDp();
                $number2 = $this->synchronizeTag();
                $number3 = $this->synchronizeUser();
                $msg = "同步用户数:".$number1.",同步部门数:".$number2.",同步标签数:".$number3."!";
                break;
        }
        return $this->success("同步成功",'',$msg);
    }


}